package com.engine.zhlx.ec.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.axis.encoding.Base64;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.zhlx.duss.utils.PropUtil;
import weaver.interfaces.zhlx.duss.utils.SrmPMPUtil;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2023年08月22日 11:45
 */
public class EcDataUtil {

    private static final JSONObject propVal = PropUtil.getPropVal("zhlxt6");
    private static final String URL = propVal.getString("url");
    private static final String USERNAME = propVal.getString("username");
    private static final String PASSWORD = propVal.getString("password");

    private static final Map<String, String> STRING_MAP = new HashMap();

    static {
        STRING_MAP.put("SaveFundingPlan", "/t6erp/rest/saveFundingPlan");
    }

    public static JSONObject sendOKHttpRequest(String apiType, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "failure";
        String message = "";
        String data = "";
        String apiUrl = URL + Util.null2String(STRING_MAP.get(apiType));
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Authorization", authorization)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 推送资金计划数据接口
     *
     * @param content
     * @return
     */
    public static JSONObject saveFundingPlan(JSONArray content) {
        return sendOKHttpRequest("SaveFundingPlan", content.toJSONString());
    }

    //根据表单和字段获取下拉框值
    public static String getSelectname(int billid, String fieldname, String selectvalue) {
        RecordSet rs = new RecordSet();
        String sql = "select t1.selectvalue,t1.selectname from workflow_selectitem t1 left join workflow_billfield t2\n" +
                " on t1.fieldid=t2.id where abs(t2.billid)=? and t2.fieldname=? and t1.selectvalue=?";
        rs.executeQuery(sql, billid, fieldname, selectvalue);
        rs.next();
        return Util.null2String(rs.getString("selectname"));
    }


    //创建流程方法
    public static String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, String> requestMainMap) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("-----创建流程传递的参数个数--------");
        baseBean.writeLog("creatorId:" + creatorId);
        baseBean.writeLog("workflowId:" + workflowId);
        baseBean.writeLog("requestName:" + requestName);
        baseBean.writeLog("IsNextFlow:" + IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);//创建人Id
        requestInfo.setWorkflowid(workflowId);//工作流Id
        requestInfo.setDescription(requestName);//请求标题
        if ("0".equals(IsNextFlow)) {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            baseBean.writeLog("\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue());
            p++;
        }
        baseBean.writeLog("-----创建流程传递的参数个数p=" + p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);//创建请求id
            } catch (Exception e) {
                baseBean.writeLog("=======" + e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:" + rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:" + rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:" + wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:" + rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:" + requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            baseBean.writeLog(sbf.toString());
        } catch (Exception e) {
            baseBean.writeLog("错误：" + e);
        }
        return requestid;
    }

    /**
     * @Description: 获取最新版本号的workflowid
     * @Param: [formid]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/9/6
     */
    public static Map<String, String> getWorkflowId(String formid) {
        RecordSet rs = new RecordSet();
        Map<String, String> resultMap = new HashMap<>();
        rs.executeQuery("select (case when activeversionid is null then id else activeversionid end) from workflow_base " +
                "where abs(formid)=? group by (case when activeversionid is null then id else activeversionid end) ", formid);
        rs.next();
        String workflowid = Util.null2String(rs.getString(1));
        resultMap.put("workflowid", workflowid);
        rs.executeQuery("select workflowname from workflow_base where id=?", workflowid);
        rs.next();
        String workflowname = Util.null2String(rs.getString(1));
        resultMap.put("workflowname", workflowname);
        return resultMap;
    }

    public static String getMainidByRequestid(String requestid, String tablename) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + tablename + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    public static Map<String, String> getGysId(String gysbm) {
        Map<String, String> map = new HashMap<>();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id,gysqc from uf_sapgyszsj where trim(gysbm)=?", gysbm);
        rs.next();
        String id = Util.null2String(rs.getString("id"));
        String gysqc = Util.null2String(rs.getString("gysqc"));
        map.put("gysid", id);
        map.put("gysqc", gysqc);
        return map;
    }

    public static String getGsxx(String gsdm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_gsxx where trim(gsdm)=?", gsdm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 插入明细表单信息
     */
    public static boolean insertDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            keyString += key + ",";
            valueString += "'" + map.get(key) + "',";
        }

        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 插入明细表单信息
     */
    public static String convertZflx(String zflx) {
        String newzffs = "";
        switch (zflx) {
            case "0":
                newzffs = "1";
                break;
            case "1":
                newzffs = "0";
                break;
            case "2":
                newzffs = "3";
                break;
            default:
                newzffs = "null";
        }
        return newzffs;
    }

    // 流程自动提交--requestid 请求id/operator 流程操作者/结果 boolean型
    public static boolean autoSubmit(String requestid, int operator) {
        RequestService server = new RequestService();
        RequestInfo requestInfo = server.getRequest(Integer.parseInt(requestid));
        return new RequestService().nextNodeBySubmit(requestInfo, Integer.parseInt(requestid), operator, "");
    }

    public static boolean updateZjjhtbshDtl(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select jhid,cwfhjeyb,cwfhjebb,cwfhrgh,cwfhr,pldb,mxbs from uf_zjjhhzb where xglc=?", requestid);
        int counts = rs.getCounts();
        int count = 0;
        while (rs.next()) {
            String jhid = Util.null2String(rs.getString("jhid"));
            String cwfhjeyb = Util.null2String(rs.getString("cwfhjeyb"));
            String cwfhjebb = Util.null2String(rs.getString("cwfhjebb"));
            String cwfhrgh = Util.null2String(rs.getString("cwfhrgh"));
            String cwfhr = Util.null2String(rs.getString("cwfhr"));
            String pldb = Util.null2String(rs.getString("pldb"));
            String mxbs = Util.null2String(rs.getString("mxbs"));
            String sql = "update " + mxbs + " set cwfhjeyb=?,cwfhjebb=?,cwfhrgh=?,cwfhr=?,pldb=? where jhid=?";
            boolean flag = rs.executeUpdate(sql, cwfhjeyb, cwfhjebb, cwfhrgh, cwfhr, pldb, jhid);
            if (flag) {
                count++;
            }
        }
        return counts == count;
    }

    public static boolean autoSubmit(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select distinct userid from workflow_currentoperator\n" +
                " where (isremark in ('0','1','5','7','8','9') or (isremark='4' and viewtype=0))  and requestid = ?", requestid);
        rs.next();
        int operator = Util.getIntValue(rs.getString("userid"));
        RequestService server = new RequestService();
        RequestInfo requestInfo = server.getRequest(Integer.parseInt(requestid));
        return new RequestService().nextNodeBySubmit(requestInfo, Integer.parseInt(requestid), operator, "");
    }

    public static String getSrmPMPBack(String requestid, String tablename) {
        BaseBean baseBean = new BaseBean();
        RecordSet rs = new RecordSet();
        String message = "";
        String nodeCode = "";
        String fj = "";
        String nodeName = "";
        String nodeUser = "";
        int nextnodeid = 0;
        try {
            rs.executeQuery("select * from " + tablename + " where requestid=?", requestid);
            if (rs.next()) {
                String lcbh = Util.null2String(rs.getString("lcbh"));
                String fqrfjsc = Util.null2String(rs.getString("fqrfjsc"));
                String spbh = Util.null2String(rs.getString("spbh"));
                String szht = Util.null2String(rs.getString("szht"));
                String xmglsrmcf = Util.null2String(rs.getString("xmglsrmcf"));
                if (!"0".equals(xmglsrmcf) && "formtable_main_4736".equals(tablename)) {
                    baseBean.writeLog(">>>>>getSrmPMPBack>>>>>不调用SrmPMP回传接口");
                } else {
                    nodeCode += lcbh + spbh;
                    fj = fqrfjsc + szht;
                    ResourceComInfo comInfo = new ResourceComInfo();
                    rs.executeQuery("select distinct userid,nodeid from workflow_currentoperator\n" +
                            " where (isremark in ('0','1','5','7','8','9') or (isremark='4' and viewtype=0))  and requestid = ?", requestid);
                    while (rs.next()) {
                        String userid = Util.null2String(rs.getString("userid"));
                        nextnodeid = Util.getIntValue(rs.getString("nodeid"));
                        String nextnodename = SrmPMPUtil.getNodebaseNodename(nextnodeid).getString("nodename");
                        String lastname = comInfo.getLastname(userid);
                        String name = lastname + " " + nextnodename;
                        nodeName += "".equals(nodeName) ? name : "," + name;
                        String workcode = comInfo.getWorkcode(userid);
                        nodeUser += "".equals(nodeUser) ? workcode : "," + workcode;
                    }
                    JSONObject dataJson = new JSONObject();
                    dataJson.put("nodeCode", nodeCode);
                    dataJson.put("nodeName", nodeName);
                    dataJson.put("nodeUser", nodeUser);
                    dataJson.put("processId", requestid);
                    dataJson.put("status", "1");
                    dataJson.put("type", "3");
                    if (!"".equals(fj)) {
                        dataJson.put("attachment", SrmPMPUtil.getImageFile(fj));
                    }
                    dataJson.put("source", "srm");
                    baseBean.writeLog(">>>>>getSrmPMPBack>>>>>dataJson=" + dataJson);
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("jkdymc", "getSrmPMPBack");
                    dataMap.put("lcid", requestid);
                    dataMap.put("dylc", requestid);
                    dataMap.put("cz", "subimt");
                    JSONObject resultJson = SrmPMPUtil.processSpeed(dataJson, dataMap);
                    baseBean.writeLog(">>>>>getSrmPMPBack>>>>>resultJson=" + resultJson);
                    String code = Util.null2String(resultJson.getString("code"));
                    if ("success".equals(code)) {
                        JSONObject returnDataJson = JSONObject.parseObject(resultJson.getString("data"));
                        if (!"200".equals(returnDataJson.getString("code"))) {
                            message = Util.null2String(returnDataJson.getString("message"));
                        }
                    } else {
                        message = Util.null2String(resultJson.getString("message"));
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

    // 根据请求id获取表名
    public static String getTableName(String requestid) {
        RecordSet rs = new RecordSet();
        rs.execute("select t3.tablename from workflow_requestbase t1 "
                + " left join workflow_base t2 on t1.workflowid = t2.id "
                + " left join workflow_bill t3 on t2.formid = t3.id "
                + " where t1.requestid = " + requestid);
        rs.next();
        return Util.null2String(rs.getString("tablename"));
    }

    public static JSONObject getGysYhxx(String gysid, String bzwb) {
        JSONObject dataJson = new JSONObject();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select yxzhdm,yxzh,khyx,ckxj,swiftcode from uf_sapgyszsj_dt1 where mainid=? and kzm='电汇' and yxbz=? and yxqjsrq>=TO_CHAR(SYSDATE, 'YYYY-MM-DD') order by yxqksrq desc", gysid, bzwb);
        if (rs.next()) {
            String lxhdh = Util.null2String(rs.getString("yxzhdm"));
            String yxzhdh = Util.null2String(rs.getString("yxzh"));
            String khyxdh = Util.null2String(rs.getString("khyx"));
            String ckxj = Util.null2String(rs.getString("ckxj"));
            String swiftcode = Util.null2String(rs.getString("swiftcode"));
            dataJson.put("lxhdh", lxhdh);
            dataJson.put("yxzhdh", yxzhdh + ckxj);
            dataJson.put("khyxdh", khyxdh);
            dataJson.put("swiftcode", swiftcode);
        }
        rs.executeQuery("select yxzhdm,yxzh,khyx,ckxj,swiftcode from uf_sapgyszsj_dt1 where mainid=? and kzm='承兑' and yxbz=? and yxqjsrq>=TO_CHAR(SYSDATE, 'YYYY-MM-DD') order by yxqksrq desc", gysid, bzwb);
        if (rs.next()) {
            String lxhcd = Util.null2String(rs.getString("yxzhdm"));
            String yxzhcd = Util.null2String(rs.getString("yxzh"));
            String khyxcd = Util.null2String(rs.getString("khyx"));
            String ckxj = Util.null2String(rs.getString("ckxj"));
            String swiftcode = Util.null2String(rs.getString("swiftcode"));
            dataJson.put("lxhcd", lxhcd);
            dataJson.put("yxzhcd", yxzhcd + ckxj);
            dataJson.put("khyxcd", khyxcd);
            dataJson.put("swiftcode", swiftcode);
        }
     return dataJson;
    }
}
